package com.hangzhou.xyj.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.UserDao;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.event.AnimationEvent;
import com.hangzhou.xyj.event.NewMessageEvent;
import com.hangzhou.xyj.event.OperationRespEvent;
import com.hangzhou.xyj.manager.ChatManager;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.manager.NotifyManager;
import com.hangzhou.xyj.manager.ScreenManager;
import com.hangzhou.xyj.model.GroupPushMsgModel;
import com.hangzhou.xyj.model.MessageModel;
import com.hangzhou.xyj.model.type.EGroupPushType;
import com.hangzhou.xyj.model.type.EPushMessageType;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.dialog.TipsDialog;
import com.hangzhou.xyj.ui.fragment.CommunityFragment;
import com.hangzhou.xyj.ui.fragment.FindFragment;
import com.hangzhou.xyj.ui.fragment.MineFragment;
import com.hangzhou.xyj.ui.fragment.SingFragment;
import com.hangzhou.xyj.ui.fragment.StageFragment;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView.OnBackListener;
import com.hangzhou.xyj.ui.widget.MainNavTabBarView;
import com.hangzhou.xyj.ui.widget.MainNavTabBarView.OnTabSelectedListener;
import com.hangzhou.xyj.ui.widget.VisualizerView;
import com.hangzhou.xyj.utils.LogUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.AppConstants;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.hyphenate.chat.EMClient;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * 首页
 *
 * @author neo.duan
 */
public class MainActivity extends BaseActivity implements OnTabSelectedListener, View.OnClickListener, CommunityFragment.OnItemChangeListener {

    private static final long INTERVAL = 2000;  //2s间隔
    private FragmentManager mFragmentManager;
    private Fragment mCurrentFragment;
    private StageFragment mStageFragment; //戏台
    private CommunityFragment mCommFragment;  //社区
    private SingFragment mSingFragment;    //唱戏
    private FindFragment mFindFragment; //发现
    private MineFragment mMineFragment; //我
    private MainNavTabBarView mTabBar;
    private int mCommCurrentItem = 0;//社区的ViewPager当前选中的条目
    private VisualizerView mVisualizerView; //音谱View
    /**
     * 再按一次退出程序
     */
    private long exitTime = 0;
    private Bundle mBundle;

    @Override
    public void initIntentData(Intent intent) {
        mBundle = intent.getBundleExtra(DataKey.BUNDLE);

    }

    @Override
    public void initTop() {
        //自带的标题栏隐藏
        enableTop(true);
//        enableBack(true, R.drawable.ic_playing);
        enableBack(true, mVisualizerView = new VisualizerView(mContext));
        enableRightNav(false);
        setOnBackListener(new OnBackListener() {
            @Override
            public void onBack() {
                if (StringUtil.isEmpty(AppConstants.PLAYING_DRAMA_ID)) {
                    IntentManager.getInstance().goNoPlayingActivity(mContext);
                } else {
                    IntentManager.getInstance().goRestoreDramaPlayActivity(mContext, AppConstants.PLAY_LIST, AppConstants.CURRENT_PLAY_POSITION);
                }
            }
        });
        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                if (XYJApplication.getUserInfo() == null) {
                    TipsDialog dialog = new TipsDialog(mContext, "提示", "该操作需要登录才能继续，是否登录？", "确定", "取消") {
                        @Override
                        protected void OnClickNegativeButton() {
                            this.dismiss();
                        }

                        @Override
                        protected boolean OnClickPositiveButton() {
                            //跳转到我的动态
                            IntentManager.getInstance().goLoginActivity(mContext);
//                            ScreenManager.getInstance().currentActivity().finish();
                            return true;
                        }

                    };
                    dialog.show();
                    return;
                }
                IntentManager.getInstance().goPublishDynamicActivity(mContext);
            }
        });
        enableRefresh(false);
        registerEventBus();
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_main);
    }

    @Override
    public void initViews() {
        mTabBar = findView(R.id.main_tab_bar);

    }

    @Override
    public void initDatas() {
        mFragmentManager = getSupportFragmentManager();
        mTabBar.setItemSelected(2);

        //获取消息，如果有消息，则显示小红点
        int unreadMsgsCount = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        mTabBar.setRedDotDisplay(4, unreadMsgsCount > 0);
    }

    @Override
    public void initListeners() {
        mTabBar.setOnTabSelectedListener(this);
    }

    /**
     * 底部导航切换回调
     */
    @Override
    public void onTabSelected(int position) {
        enableTitle(true, mTabBar.getTextArr()[position]);
        //
        if (position == 1 && mCommCurrentItem != 0) {
            enableRightNav(true, R.drawable.ic_publish);
        } else {
            enableRightNav(false);
        }
        //控制当前显示哪个fragment
        switch (position) {
            case 0:
                if (mStageFragment == null) {
                    mStageFragment = new StageFragment();
                }
                mCurrentFragment = mStageFragment;
                break;
            case 1:
                if (mCommFragment == null) {
                    mCommFragment = new CommunityFragment();
                }
                mCurrentFragment = mCommFragment;
                mCommFragment.setOnItemChangeListener(this);
                break;
            case 2:
                if (mSingFragment == null) {
                    mSingFragment = new SingFragment();
                }
                //自定义TitleView
                View titleView = getTopBar().getTitleView();
                if (titleView == null) {
                    titleView = View.inflate(this, R.layout.layout_sing_title, null);
                    titleView.findViewById(R.id.chb_sing_title_left).setOnClickListener(this);
                    titleView.findViewById(R.id.chb_sing_title_right).setOnClickListener(this);
                    titleView.findViewById(R.id.tv_sing_title_left).setOnClickListener(this);
                    titleView.findViewById(R.id.tv_sing_title_right).setOnClickListener(this);
                }
                getTopBar().enableTitle(true, titleView);
                mCurrentFragment = mSingFragment;
                break;
            case 3:
                if (mFindFragment == null) {
                    mFindFragment = new FindFragment();
                }
                mCurrentFragment = mFindFragment;
                break;
            case 4:
                if (mMineFragment == null) {
                    mMineFragment = new MineFragment();
                }
                mCurrentFragment = mMineFragment;
                break;
            default:
                break;
        }
        //检查mFragmentManager是否添加，未添加则添加
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        //设置显示动画
//        transaction.setCustomAnimations(R.anim.slide_in_from_right,R.anim.slide_out_from_left);
        Fragment fragment = mFragmentManager.findFragmentByTag(position + "");
        if (fragment == null) {
            transaction.add(R.id.main_container, mCurrentFragment, position + "");
        }
        //显示当前，其他隐藏
        transaction.show(mCurrentFragment);
        List<Fragment> fragmentList = mFragmentManager.getFragments();
        if (fragmentList != null && fragmentList.size() > 0) {
            for (int i = 0; i < fragmentList.size(); i++) {
                if (i == position) continue;
                Fragment tagFragment = mFragmentManager.findFragmentByTag(i + "");
                if (tagFragment != null) {
                    transaction.hide(tagFragment);
                }
            }
        }
        transaction.commitAllowingStateLoss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > INTERVAL) {
                exitTime = System.currentTimeMillis();
                ToastUtil.show("再按一次退出程序");
            } else {
                XYJApplication.getInstance().setUserInfo(null);
                //退出环信
                ChatManager.getInstance().logout();
                ScreenManager.getInstance().popAllActivity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onClick(View view) {
        CheckBox leftChb = (CheckBox) getTopBar().getTitleView().findViewById(R.id.chb_sing_title_left);
        CheckBox rightChb = (CheckBox) getTopBar().getTitleView().findViewById(R.id.chb_sing_title_right);
        switch (view.getId()) {
            case R.id.chb_sing_title_left: //榜单
            case R.id.tv_sing_title_left:
                leftChb.setChecked(true);
                rightChb.setChecked(false);
                //显示榜单
                if (mCurrentFragment instanceof SingFragment) {
                    ((SingFragment) mCurrentFragment).showLayout(SingFragment.LIST_TYPE);
                }
                break;
            case R.id.chb_sing_title_right: //点戏
            case R.id.tv_sing_title_right:
                leftChb.setChecked(false);
                rightChb.setChecked(true);
                if (XYJApplication.getUserInfo() == null) {
                    IntentManager.getInstance().goLoginActivity(mContext);
                    return;
                }
                //显示点戏
                if (mCurrentFragment instanceof SingFragment) {
                    ((SingFragment) mCurrentFragment).showLayout(SingFragment.DRAMA_TYPE);
                }
                break;
        }
    }

    @Override
    public void itemChange(int position) {
        mCommCurrentItem = position;
        if (position == 0) {
            enableRightNav(false);
        } else {
            enableRightNav(true, R.drawable.ic_publish);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //如果是退出登录操作的
        if ("cancel".equals(getIntent().getStringExtra(DataKey.INTENT_TAG))) {
            onTabSelected(2);//戏台选中
        }
    }

    @Override
    protected void onResume() {
        LogUtil.d(TAG, "onResume()");
        super.onResume();
        //通知栏进来要做的
        if (mBundle != null) {
            String path = mBundle.getString(DataKey.URL);
            String message = mBundle.getString(DataKey.MESSAGE);
            int pushType = mBundle.getInt(DataKey.PUSH_TYPE);
            if (Integer.valueOf(CommonPreferences.getUserId(mContext)) != -1) {//登录的
                Intent i = new Intent(mContext, MyMessageActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mContext.startActivity(i);
            } else {
                Intent it;
                if (StringUtil.isEmpty(path)) {//无url的
                    it = new Intent(mContext, MyOfficalMessageActivity.class);
                    GroupPushMsgModel msgModel = new GroupPushMsgModel();
                    msgModel.setMsgTime(System.currentTimeMillis());//时间
                    msgModel.setGroupPic("drawable://" + R.drawable.ic_offical_head);//头像
                    msgModel.setMsgType(EGroupPushType.NOTIFICATION.getValue());//类型
                    msgModel.setContent(message);
                    msgModel.setToId("all");
                    it.putExtra(DataKey.OBJ, msgModel);
                    it.putExtra(DataKey.PUSH_TYPE, pushType);
                } else {//有url的
                    it = new Intent(mContext, WebActivity.class);
                    it.putExtra(DataKey.INDEX, path);
                    it.putExtra(DataKey.PUSH_TYPE, pushType);
                    it.putExtra(DataKey.TITLE, message);
                }
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mContext.startActivity(it);
                resetNotificationCount(EPushMessageType.valueOf(pushType));
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(OperationRespEvent event) {
        if (event.getTag().toString().equals("LoginActivity")) {
            CheckBox leftChb = (CheckBox) getTopBar().getTitleView().findViewById(R.id.chb_sing_title_left);
            CheckBox rightChb = (CheckBox) getTopBar().getTitleView().findViewById(R.id.chb_sing_title_right);
            if (!event.isSuccess()) {
                leftChb.setChecked(true);
                rightChb.setChecked(false);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AnimationEvent event) {
        if (event.isPlay()) {
            mVisualizerView.startAnim();
        } else {
            mVisualizerView.stopAnim();
        }
    }

    /**
     * 收到新消息事件，更新小红点
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNewMessageEvent(NewMessageEvent event) {
        LogUtil.d(TAG, "收到新消息");
        Activity currentActivity = ScreenManager.getInstance().currentActivity();
        if (currentActivity == null) {
            return;
        }
        //当前页面在有关消息页面，则不触发显示小红点
        if (currentActivity instanceof MyMessageActivity
                || currentActivity instanceof ChatActivity
                || mCurrentFragment instanceof MineFragment) {
            return;
        }
        mTabBar.setRedDotDisplay(4, true);
        //触发通知栏通知
        NotifyManager.getInstance().notify(mContext,
                new MessageModel(event.getMessageType().getValue(), System.currentTimeMillis()),
                new Intent(mContext, MyMessageActivity.class));
    }

    /**
     * 重置
     *
     * @param pushMessageType
     */
    private void resetNotificationCount(EPushMessageType pushMessageType) {
        switch (pushMessageType) {
            case SINGLE_CHAT:
                NotifyManager.mSingleChatCount = 0;//重置
                break;
            case GROUP_CHAT:
                NotifyManager.mGroupChatCount = 0;
                break;
            case ADD_GROUP:
                NotifyManager.mAddGroupCount = 0;
                break;
            default:
            case SYSTEM:
                NotifyManager.mSystemCount = 0;
                break;
        }
    }
}
